import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  CardMedia,
  CardActions,
  Button,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  TextField,
  MenuItem,
  Pagination,
  Fab,
} from '@mui/material';
import {
  Edit,
  Delete,
  Visibility,
  Add,
  Search,
  FilterList,
  Image,
  VideoFile,
} from '@mui/icons-material';
import { useContent } from '../../hooks/useContent';
import { ContentEditor } from './components';
import { Content, ContentListItem, ContentType, ContentQueryParams } from '../../types';

const MyContents: React.FC = () => {
  const { getMyContents, deleteContent, viewContent, loading } = useContent();
  const [contents, setContents] = useState<ContentListItem[]>([]);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedContent, setSelectedContent] = useState<Content | null>(null);
  const [editorOpen, setEditorOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [contentToDelete, setContentToDelete] = useState<ContentListItem | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // 搜索和筛选状态
  const [searchTitle, setSearchTitle] = useState('');
  const [contentTypeFilter, setContentTypeFilter] = useState<string>('all');
  const [sortBy, setSortBy] = useState<string>('created_at');

  // 加载内容列表
  const loadContents = async (page: number = 1) => {
    try {
      setError(null);
      const params: ContentQueryParams = {
        page,
        size: 12,
        ...(searchTitle && { title: searchTitle }),
        ...(contentTypeFilter !== 'all' && { contentType: contentTypeFilter }),
        orderBy: sortBy as any,
      };

      const response = await getMyContents(params);
      setContents(response.contents || []);
      setTotalPages(response.totalPages || 0);
      setCurrentPage(page);
    } catch (err) {
      setError('加载内容失败，请稍后重试');
      console.error('加载内容失败:', err);
    }
  };

  // 初始加载
  useEffect(() => {
    loadContents();
  }, []);

  // 搜索和筛选
  const handleSearch = () => {
    loadContents(1);
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    loadContents(page);
  };

  // 编辑内容
  const handleEditContent = async (content: ContentListItem) => {
    try {
      setError(null);
      // 调用API获取完整的内容详情
      const contentDetail = await viewContent(content.id);
      
      // 将ContentDetail转换为Content格式
      const fullContent: Content = {
        id: contentDetail.id,
        userId: contentDetail.userId,
        contentType: contentDetail.contentType,
        title: contentDetail.title,
        textContent: contentDetail.textContent,
        coverUrl: contentDetail.coverUrl,
        uploadStatus: content.uploadStatus, // 从列表项获取
        imageUrls: contentDetail.images.map(img => img.imageUrl),
        images: contentDetail.images, // 保存完整的图片信息
        videoUrls: contentDetail.videos.map(video => video.videoUrl),
        likeCount: contentDetail.likeCount,
        commentCount: contentDetail.commentCount,
        viewCount: contentDetail.viewCount,
        isPublished: contentDetail.isPublished,
        isLiked: contentDetail.isLiked,
        createdAt: contentDetail.createdAt,
        updatedAt: contentDetail.updatedAt,
      };
      
      setSelectedContent(fullContent);
      setEditorOpen(true);
    } catch (err) {
      setError('获取内容详情失败，请稍后重试');
      console.error('获取内容详情失败:', err);
    }
  };

  const handleEditorClose = () => {
    setEditorOpen(false);
    setSelectedContent(null);
  };

  const handleContentUpdate = (updatedContent: Content) => {
    // 更新列表中的内容
    setContents(prev => prev.map(content => 
      content.id === updatedContent.id ? {
        ...content,
        title: updatedContent.title,
        updatedAt: updatedContent.updatedAt,
      } : content
    ));
    setSuccess('内容更新成功');
  };

  // 删除内容
  const handleDeleteContent = (content: ContentListItem) => {
    setContentToDelete(content);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!contentToDelete) return;

    try {
      setError(null);
      await deleteContent(contentToDelete.id);
      setContents(prev => prev.filter(content => content.id !== contentToDelete.id));
      setSuccess('内容删除成功');
      setDeleteDialogOpen(false);
      setContentToDelete(null);
    } catch (err) {
      setError('删除失败，请稍后重试');
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  // 获取上传状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'COMPLETED': return 'success';
      case 'UPLOADING': return 'warning';
      case 'FAILED': return 'error';
      default: return 'default';
    }
  };

  // 获取上传状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'COMPLETED': return '已完成';
      case 'UPLOADING': return '上传中';
      case 'UPDATING': return '更新中';
      case 'FAILED': return '失败';
      case 'PENDING': return '待处理';
      default: return status;
    }
  };

  return (
    <Box sx={{ maxWidth: 1200, mx: 'auto', p: 3 }}>
      {/* 页面标题 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Typography variant="h4" component="h1">
          我的内容
        </Typography>
        <Button
          variant="contained"
          startIcon={<Add />}
          href="/create"
          sx={{ borderRadius: 2 }}
        >
          创建内容
        </Button>
      </Box>

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}>
            <TextField
              label="搜索标题"
              value={searchTitle}
              onChange={(e) => setSearchTitle(e.target.value)}
              size="small"
              sx={{ minWidth: 200 }}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            />
            
            <TextField
              select
              label="内容类型"
              value={contentTypeFilter}
              onChange={(e) => setContentTypeFilter(e.target.value)}
              size="small"
              sx={{ minWidth: 120 }}
            >
              <MenuItem value="all">全部</MenuItem>
              <MenuItem value="IMAGE">图文</MenuItem>
              <MenuItem value="VIDEO">视频</MenuItem>
            </TextField>

            <TextField
              select
              label="排序方式"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              size="small"
              sx={{ minWidth: 120 }}
            >
              <MenuItem value="created_at">创建时间</MenuItem>
              <MenuItem value="like_count">点赞数</MenuItem>
            </TextField>

            <Button
              variant="contained"
              startIcon={<Search />}
              onClick={handleSearch}
              disabled={loading}
            >
              搜索
            </Button>
          </Box>
        </CardContent>
      </Card>

      {/* 错误和成功提示 */}
      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}
      
      {success && (
        <Alert severity="success" sx={{ mb: 2 }} onClose={() => setSuccess(null)}>
          {success}
        </Alert>
      )}

      {/* 内容列表 */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      ) : contents.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <Typography variant="h6" color="text.secondary" gutterBottom>
            暂无内容
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
            创建你的第一个内容吧
          </Typography>
          <Button
            variant="contained"
            startIcon={<Add />}
            href="/create"
            size="large"
          >
            创建内容
          </Button>
        </Box>
      ) : (
        <>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 3 }}>
            {contents.map((content) => (
              <Card key={content.id} sx={{ width: { xs: '100%', sm: 'calc(50% - 12px)', md: 'calc(33.33% - 16px)' } }}>
                {/* 封面图片 */}
                <Box sx={{ position: 'relative', height: 200 }}>
                  {content.coverUrl ? (
                    <CardMedia
                      component="img"
                      height="200"
                      image={content.coverUrl}
                      alt={content.title}
                      sx={{ objectFit: 'cover' }}
                    />
                  ) : (
                    <Box
                      sx={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        bgcolor: 'grey.100',
                        color: 'grey.500',
                      }}
                    >
                      {content.contentType === ContentType.IMAGE ? (
                        <Image sx={{ fontSize: 48 }} />
                      ) : (
                        <VideoFile sx={{ fontSize: 48 }} />
                      )}
                    </Box>
                  )}
                  
                  {/* 内容类型标签 */}
                  <Chip
                    label={content.contentType === ContentType.IMAGE ? '图文' : '视频'}
                    color={content.contentType === ContentType.IMAGE ? 'primary' : 'secondary'}
                    size="small"
                    sx={{ position: 'absolute', top: 8, left: 8 }}
                  />
                  
                  {/* 上传状态标签 */}
                  <Chip
                    label={getStatusText(content.uploadStatus)}
                    color={getStatusColor(content.uploadStatus) as any}
                    size="small"
                    sx={{ position: 'absolute', top: 8, right: 8 }}
                  />
                </Box>

                <CardContent>
                  <Typography variant="h6" noWrap gutterBottom>
                    {content.title || '无标题'}
                  </Typography>

                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                    <Typography variant="caption" color="text.secondary">
                      {formatDate(content.createdAt)}
                    </Typography>
                    <Box sx={{ display: 'flex', gap: 1 }}>
                      <Chip label={`${content.likeCount} 赞`} size="small" variant="outlined" />
                      <Chip label={`${content.viewCount} 看`} size="small" variant="outlined" />
                    </Box>
                  </Box>
                </CardContent>

                <CardActions sx={{ justifyContent: 'space-between', px: 2, pb: 2 }}>
                  <Box>
                    <IconButton
                      size="small"
                      onClick={() => handleEditContent(content)}
                      color="primary"
                    >
                      <Edit />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDeleteContent(content)}
                      color="error"
                    >
                      <Delete />
                    </IconButton>
                  </Box>
                  <Chip
                    label={content.isPublished ? '已发布' : '已删除'}
                    color={content.isPublished ? 'success' : 'default'}
                    size="small"
                  />
                </CardActions>
              </Card>
            ))}
          </Box>

          {/* 分页 */}
          {totalPages > 1 && (
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
              <Pagination
                count={totalPages}
                page={currentPage}
                onChange={handlePageChange}
                color="primary"
                size="large"
              />
            </Box>
          )}
        </>
      )}

      {/* 内容编辑器 */}
      <ContentEditor
        open={editorOpen}
        content={selectedContent}
        onClose={handleEditorClose}
        onUpdate={handleContentUpdate}
      />

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除内容 "{contentToDelete?.title}" 吗？此操作不可撤销。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>
            取消
          </Button>
          <Button onClick={confirmDelete} color="error" autoFocus>
            确认删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default MyContents; 